package com.example.wac.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.example.wac.constant.Constant;
import com.example.wac.dto.GoodsDto;
import com.example.wac.entity.Goods;
import com.example.wac.enums.ErrorCode;
import com.example.wac.service.GoodsService;
import com.example.wac.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.*;

/**
 * @author wuancheng
 * @description
 * @date 2022-01-18 16:29:00
 */

@Slf4j
public class InitGoodsReadListener extends AnalysisEventListener<GoodsDto> {

    private static final GoodsService goodsService;

    /**
     * spring管理的bean都是可以被实例化的类 抽象类无法实例化 不能通过spring直接注入bean
     * 1.抽象类需要通过ApplicationContext获取上下文(new出来的)主动获取bean（不能通过@Autowired注入）
     * 2.setter方式注入
//     * 3.构造函数注入
     */
    static {
        goodsService = SpringUtils.getBean(GoodsService.class);
    }

    /**
     * 导入成功集合
     */
    private List<GoodsDto> dtoList = new ArrayList<>();

    /**
     * 合格商品待存入集合
     */
    private List<Goods> goods = new ArrayList<>();

    /**
     * 商品map，key为商品名称，value为Excel所在行数
     */
    private final Map<String, Integer> goodsNameMap = new HashMap<>();

    @Override
    public void invoke(GoodsDto goodsDto, AnalysisContext analysisContext) {
        // 获取读取的当前行数
        int row = analysisContext.readRowHolder().getRowIndex() + 1;
        String goodsName = goodsDto.getGoodsName();
        if (goodsNameMap.containsKey(goodsName)){
            throw ErrorCode.GOODS_INIT_ERROR.getAppException("第" + row + "商品名称[" + goodsName + "]与第" + goodsNameMap.get(goodsName) + "行重复");
        }
        goodsNameMap.put(goodsName,row);
        dtoList.add(goodsDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Set<String> goodsNameSet = goodsNameMap.keySet();
        if (goodsNameSet.size() > Constant.ExcelTemplate.MAX_EXCEL_COUNT){
            throw ErrorCode.EXPORT_NUM_MORE_THAN_MAX.getAppException(goodsNameSet.size());
        }
        // 导入的商品是否已数据库中存在
        List<Goods> list = new LambdaQueryChainWrapper<>(goodsService.getBaseMapper())
                .in(Goods::getGoodsName, goodsNameSet)
                .list();
        if (CollectionUtils.isNotEmpty(list)){
            throw ErrorCode.GOODS_INIT_ERROR.getAppException("当前商品" + list.toString() + "已存在");
        }
        // 商品列表存入数据库
        dtoList.forEach(goodsDto -> {
            Goods goodsSave = new Goods();
            BeanUtils.copyProperties(goodsDto,goodsSave);
            goods.add(goodsSave);
        });
        goodsService.saveBatch(goods);
    }
}
